package com.homesoft.runtime.metadata.modle;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.thoughtworks.xstream.annotations.XStreamOmitField;

public abstract  class KeyedCollection<TKey, TItem> implements Collection<TItem> {
	@XStreamOmitField 
	private Map<TKey, TItem> dict;
	
	public KeyedCollection(){
		dict = new HashMap<TKey,TItem>();
	}
	
	public TItem get(TKey key){
		return dict.get(key);
	}
	
	@Override
	public boolean add(TItem e) {
		return this.dict.values().add(e);
	}
	@Override
	public boolean addAll(Collection<? extends TItem> c) {
		return this.dict.values().addAll(c);
	}
	@Override
	public void clear() {
		this.dict.values().clear();
	}
	@Override
	public boolean contains(Object o) {
		return this.dict.values().contains(o);
	}
	@Override
	public boolean containsAll(Collection<?> c) {
		return this.dict.values().containsAll(c);
	}
	@Override
	public boolean isEmpty() {
		return this.dict.isEmpty();
	}
	@Override
	public Iterator<TItem> iterator() {
		return this.dict.values().iterator();
	}
	@Override
	public boolean remove(Object o) {
		return this.dict.values().remove(o);
	}
	@Override
	public boolean removeAll(Collection<?> c) {
		return this.dict.values().removeAll(c);
	}
	@Override
	public boolean retainAll(Collection<?> c) {
		return this.dict.values().retainAll(c);
	}
	@Override
	public int size() {
		return this.dict.size();
	}
	@Override
	public Object[] toArray() {
		
		return this.dict.values().toArray();
	}
	@Override
	public <T> T[] toArray(T[] a) {
		return this.dict.values().toArray(a);
	}
	
	public boolean ContainsKey(TKey key){
		return this.dict.containsKey(key);
	}
	public void add(TKey key, TItem item){
		this.dict.put(key, item);
	}
	public boolean ChangeItemKey(TItem item, TKey newKey) {
		if (!this.contains(item))
	    {
	        //ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist);
	    }
	    TKey keyForItem = this.GetKeyForItem(item);
	    if (keyForItem!= null && !keyForItem.equals(newKey))
	    {
	        if (newKey != null)
	        {
	            this.add(newKey, item);
	        }
	        if (keyForItem != null)
	        {
	            this.RemoveKey(keyForItem);
	        }
	        return true;
	    }
		return false;
	}
	public void RemoveKey(TKey key){
		this.dict.remove(key);
	}
	public abstract TKey GetKeyForItem(TItem item);
}